<?php

namespace App\Http\Controllers\Index;

use Illuminate\Http\Request;
use shishao\huobiApi\Huobi\HuobiApi;
use App\Jobs\HbPricePodcast;
use Illuminate\Support\Facades\DB;
use App\Jobs\ExecTranPodcast;
class HbApiController extends BaseController
{
    protected $huobi;
    public function __construct(HuobiApi $huobi)
    {
        $this->huobi=$huobi;
    }
    //获取价格插入数据库
    public function price()
    {
        $add=$this->huobi->get_market_trade('xrpusdt');
        $price=$add->tick->data[0]->price;
        HbPricePodcast::dispatch($price);
    }
    //开始交易和停止交易
    public function bus(Request $request)
    {
        $uid=auth()->user()->user_id;
        $ex_id=$request->ex_id;
        $curr=$request->curr;
        $account=$request->account;
        $status=$request->status;
        if($ex_id==1){
            $username=DB::table('ex_username')->where(['user_id'=>$uid,'ex_id'=>$ex_id])->value('username');
            if(empty($username)){
                return $this->error('账号不存在');
            }
            $first=DB::table('coin_conf')->where(['ex_id'=>$ex_id,'user_id'=>$uid,'account_id'=>$account,'coin_name'=>$curr])->first();
            if(empty($first)){
               return $this->error('请先设置币种参数');
            }
           $data=$this->huobi->get_market_trade(strtolower($curr).'usdt');
           $price=$data->tick->data[0]->price;
           //获取账户id
          $account_id=$this->huobi->get_account_accounts();
            $acc_id=0;
            foreach ($account_id->data as $v){
               if($v->type=='spot'){
                   $acc_id=$v->id;
                   break;
               }
            }
            //获取余额
            $balance=$this->huobi->get_balance($acc_id);
            $bal_list=$balance->data->list;
            $bal=0;
            foreach($bal_list as $v){
                if($v->currency==strtolower($curr)){
                    $bal=$v->balance;
                    break;
                }
            }
          $res=DB::table('coin_conf')->where(['ex_id'=>$ex_id,'user_id'=>$uid,'account_id'=>$account,'coin_name'=>$curr])->update([
               'op_status'=>$status,
               'last_trade_price'=>$price,
               'last_trade_time'=>time(),
               'balance'=>$bal,
               'am_usdt'=>$price,
               'acc_id'=>$acc_id
           ]);
         if($res){
            return $this->success('操作成功');
         }else{
             return $this->error('操作失败');
         }
        }
    }
    //执行交易
    public function execTran()
    {
        $confList=DB::table('coin_conf')->where(['op_status'=>1,'status'=>0])->get();
        if(!$confList->isEmpty()){
            ExecTranPodcast::dispatch($confList);
        }
    }

}
